#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <netinet/in.h>
#include <getopt.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <netinet/tcp.h>

#include "sqlite3.h"
#include "ds18b20.h"
#include "dbs.h"
#include "cJSON.h"
#include "connect.h"

int pack_json(char *buf,int size,char *id,float temp,char *timep);
int get_data(char *buf,int size);

void print_usage(char *progname)
{
	printf("%s usage:\n",progname);
	printf("-p(port):sepcify server listen port.\n");
	printf("-h(help):print this information.\n");
	printf("-i(address):sepcify server address.\n");

	return ;
}

int get_devid(char *id,int size)
{
    strncpy(id,"rpi_002",size);
}

int get_time(char *timep)
{
    time_t 	timer;
    struct tm 	*plocaltime = NULL;
    char   	*tmp=NULL;

    timer = time(NULL);
    plocaltime = localtime(&timer);

    //strcpy(timep, asctime(tblock));

    sprintf(timep,"%d-%d-%d %d:%d:%d",plocaltime->tm_year+1900,plocaltime->tm_mon+1,plocaltime->tm_mday,plocaltime->tm_hour,plocaltime->tm_min,plocaltime->tm_sec);

    if((tmp=strstr(timep,"\n")))
    {
	    *tmp = '\0';
    }
}

void sig_handler(int signum)
{
	if(signum == SIGPIPE)
	{
		printf("socket dsiconnect!\n");
	}
}

int re_conn(int sock)
{
	struct tcp_info		info;
	int			len=sizeof(info);
	getsockopt(sock,IPPROTO_TCP,TCP_INFO,&info,(socklen_t *)&len);
	if((info.tcpi_state == TCP_ESTABLISHED))
	{
		return 0;
	}
	else
	{
		printf("TCP disconnect! start reconnecting... \n");
		return 1;
	}
}


int main(int argc,char **argv)
{
	int			conn_fd=-1;
	int			connected = 0;
	int			rv=-1;
	char			*servip=NULL;
	int			port=0;
	int			ch;
	char			buf[1024];
	float			temperature;
	char                 	timep[32];
	char                 	devid[8];
	int 			row;
#if 1
	struct option		opts[]={
		{"ipaddr",required_argument,NULL,'i'},
		{"port",required_argument,NULL,'p'},
		{"help",no_argument ,NULL,'h'},
		{0,0,0,0}
	
	};


	signal(SIGPIPE,sig_handler);


	while((ch=getopt_long(argc,argv,"p:i:h",opts,NULL))!=-1)
	{
		switch(ch)
		{
			case 'p':
				port=atoi(optarg);
				break;

			case 'i':
				servip=optarg;
				break;

			case 'h':
				print_usage(argv[0]);
				return 0;
		}

	}

	if(!port)
	{
		print_usage(argv[0]);
		return -1;
	}
#endif
	


#if 1
	

	while(1)
	{
		if(!connected)
		{
			conn_fd = socket_connect(servip,&port);
			if(conn_fd<0)
			{
				connected=0;
				sleep(10);
				get_data(buf,sizeof(buf));
				//没连接上服务器时，把数据上传到数据库
				printf("-----Upload data to the <database>!-----\n");
				send_to_sqlite3(buf);
				continue;

			}
			else
			{
				connected = 1;

				printf("<Successfully connected to server!>\n");

				//获取数据库行数,即与服务器断开时，存储到数据库中的数据条数
				get_dbs_rows(&row);
				while(row)
				{

					//从数据库获取数据
					memset(devid,0,sizeof(devid));
					memset(timep,0,sizeof(timep));
					get_sqlite_data(devid,timep,&temperature);
					//printf("id:%s  time:%s  t:%.3f\n",devid,timep,temperature);
					//获取到数据后，把数据以json格式上传到服务器
					pack_json(buf,sizeof(buf),devid,temperature,timep);
					printf("sqlite JSON String:%s\n",buf);

					printf("-----Upload data to the <server>!-----\n");
					write(conn_fd,buf,sizeof(buf));
					delete_data();
					//上传一条数据就从数据库删除一条数据
					row--;

					sleep(2);
				}
			}
		}

		memset(buf,0,sizeof(buf));
		get_data(buf,sizeof(buf));


		//re_conn()函数用来判断与服务器是否是连接状态，是连接状态则把数据上传到服务器。断开状态则把数据上传到数据库
		int disconn = re_conn(conn_fd);
		if(!disconn)
		{
			printf("-----Upload data to the <server>!-----\n");
			write(conn_fd,buf,sizeof(buf));
		}
		else
		{
			printf("-----Upload data to the <database>!-----\n");
			send_to_sqlite3(buf);
			connected = 0;

		}

	
		sleep(10);


	}
#endif

}

int get_data(char *buf,int size)
{
	float			temperature;
	char                 	timep[32];
	char                 	devid[8];
	int			rv=-1;

	get_devid(devid, sizeof(devid));
	get_time(timep);
	rv = get_temperature(&temperature);
	//printf("temp:%.3f\n",temperature);
	
	pack_json(buf,size,devid,temperature,timep);
	printf("JSON String:%s\n",buf);


}




int pack_json(char *buf,int size,char *id,float temp,char *timep)
{
    cJSON *root = NULL;
    if(!buf || size<=0 || !id)
    {
        printf("Invalid input arguments\n");
        return -1;
    }

    root = cJSON_CreateObject();

    cJSON_AddItemToObject(root, "id",cJSON_CreateString(id));
    cJSON_AddStringToObject(root,"time",timep);
    cJSON_AddNumberToObject(root,"temperature",temp);

    strncpy(buf,cJSON_Print(root),size);   //将数据拷贝到buf中去


    cJSON_Delete(root);

    return 0;
}





















